<template>

  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>权限管理系统</span>

      </div>
      
    </template>
        <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        
      >
        <el-form-item label="账号" prop="account">
          <el-input v-model="ruleForm.account" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
                  v-model="ruleForm.password"
                  type="password"
                  placeholder="请输入密码"
                  show-password
              />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="login()">
            登录
          </el-button>
        </el-form-item>
        
      </el-form>
  </el-card>



    
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage } from 'element-plus'
  //引入路由
  import {useRouter} from 'vue-router'
  //引入登录小仓库
  import loginStore from '../../store/modules/login.ts';

  
  //定义接口
  interface RuleForm {
    account: string
    password: string
  }

  //获取路由器
  let router=useRouter();
  

  const ruleFormRef = ref<RuleForm>()
  //使用接口 并且 为每一个文本框赋 默认值
  const ruleForm = reactive<RuleForm>({
    account: 'user',
    password: '123456'
  })
  
  //校验文本框的内容
  const rules = reactive<FormRules<RuleForm>>({
    account: [
      { required: true, message: '账号不能为空', trigger: 'blur' },
      { min: 3, max: 10, message: '长度在3到10之间', trigger: 'blur' },
    ],
    password: [
      {
        required: true,
        message: '密码不能为空',
        trigger: 'change',
      },
    ]
  })



  //登录方法
  let login= async ()=>{
    //阻塞form 表单的校验 必须完成之后才能往下走 因为validate是一个async方法
    await ruleFormRef.value.validate();
    try {
      //阻塞拿到结果才往下走
      await loginStore().userLogin(ruleForm);
      //弹框
      ElMessage({
          showClose: true,
          message: '登录成功',
          type: 'success',
      })
      //跳转根路径
      router.push("/")  
    } catch (error) {
        ElMessage({
          showClose: true,
          message: (error as Error).message,
          type: 'error',
        })
    }
  }

  </script>
  